<?php
class My_LoginController extends Mediad2_Controller_Action
{	
	/**
	 * var
	 */
	private $autologin 		 = null;      //是否两周之内登陆的状态
	private $email     		 = null;
	private $pwd       		 = null;
	private $message;
	private $title;
	private $Reurl 		  	 = "login";
	private $Retitle 	  	 = "修改失败";
	private $Retime  	  	 = 50;
	
	private $serviceUser;
	
	public function init()
	{
		parent::init();
		$this->serviceUser = new Mediad2_Service_Admin_User();
		
		//email
		if (isset($this->httpdata['email'])) {
			$this->email = $this->httpdata['email'];
		}
		
		//pwd
		if (isset($this->httpdata['pwd'])) {
			$this->pwd = $this->httpdata['pwd'];
		}
	}
	
	
	//--------------------------------------------------
	// login 公开接口
	//--------------------------------------------------
	
	/**
	 * index
	 */
	public function indexAction()
	{
		$cookie = $this->cookieMethod("get", "email_cookie");
		if (isset($cookie)) {
			$this->pageview->assign ("email_cookie",$cookie);
		}
		$this->helper->setPageView($this->pageview, WEB_TITLE, "login", null);
	}
	 		
	//--------------------------------------------------
	// 私有方法
	//--------------------------------------------------
	
	public function loginAction(){
		$this->loginSystem();
	}
	
	/**
	 * login system
	 */
	private function loginSystem()
	{
		//var
		if ((isset($this->httpdata['autologin'])) && (!empty($this->httpdata['autologin'])) ) {
			$this->autologin = $this->httpdata['autologin'];
		}
		$issuccess = null;	//默认为成功
		//登录
		$result = $this->serviceUser->loginByEmail($this->email, $this->pwd);
		if ($result->getCode() == $result::CODE_SUCCESS) {
			$registry = Zend_Registry::getInstance();
			$haveUser = $registry->auth->hasIdentity();
			$identity =  $registry->auth->getIdentity();
			//判断是否记住我，并保存email
			if(!empty($this->httpdata['autologin'])){
				$this->loginCookieConfigure("save");
			}else{
				$this->loginCookieConfigure("del");
			}
			if ($haveUser) {
				if($identity->isadmin==1){
					$this->_redirect(WEB_PATH.'admin/navigate');
				}else{
					$this->_redirect(WEB_PATH.'my/dashboard');
				}
			}else{
				$issuccess = "2";
			}
			//成功登陆
		}else{
			//用户不存在
			$issuccess = "2";
		}
		$this->pageview->assign ("issuccess",$issuccess);
		$this->helper->setPageView($this->pageview, WEB_TITLE, "login", null);
		
	}
	
	/*
	 * 保存cookie和删除cookie的私有方法
	 */
	private function loginCookieConfigure($act,$pwd = '')
	{
		switch ($act) {
			case 'save':
				$this->cookieMethod($act, 'email_cookie', $this->email);
				break;
			case 'del':
				$this->cookieMethod($act, "email_cookie");
				break;
		}
	}
}